package com.css.zfzx.fwsjcj.modules.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.division.service.DivisionService;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.page.login.security.LoginSecretPool;
import com.css.bpm.platform.page.login.viewobjects.PwdCheck;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.fwsjcj.modules.user.entity.FwUserEntity;
import com.css.zfzx.fwsjcj.modules.user.service.FwUserService;
import com.css.zfzx.fwsjcj.modules.user.vo.UserQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.annotations.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.repository.query.Param;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 房屋-用户信息Controller
 *
 * @author Leon
 */
@RestController
@EnableJpaAuditing
@RequestMapping("/fw/user")
@Slf4j
public class FwUserController {
    @Autowired
    private FwUserService fwUserService;
    @Autowired
    DivisionService divisionService;

    /***
     * 注册用户APP
     * @param fwUserEntity
     * @return
     */
    @PostMapping("userApp")
    public RestResponse saveUserApp(@RequestBody FwUserEntity fwUserEntity) {
        if (fwUserEntity == null) {
            return RestResponse.fail("保存用户信息不能为空");
        }
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            fwUserService.saveUserApp(fwUserEntity);
            json.put("message", "注册成功,请等待管理员审核!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "注册失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /***
     * 注册用户
     * @param fwUserEntity
     * @return
     */
    @PostMapping("user")
    public RestResponse saveUser(@RequestBody FwUserEntity fwUserEntity) {
        if (fwUserEntity == null) {
            return RestResponse.fail("保存用户信息不能为空");
        }
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            if (!StringUtils.isEmpty(fwUserEntity.getUserName())) {
                FwUserEntity byUserName = fwUserService.findByUserName(fwUserEntity.getUserName());
                if (!StringUtils.isEmpty(byUserName)) {
                    return RestResponse.fail("手机号已存在");
                }
            }
            if (!StringUtils.isEmpty(fwUserEntity.getIdNumber())) {
                FwUserEntity byIdNumber = fwUserService.findByIdNumber(fwUserEntity.getIdNumber());
                if (!StringUtils.isEmpty(byIdNumber)) {
                    return RestResponse.fail("身份证号已存在");
                }
            }
            if (!StringUtils.isEmpty(fwUserEntity.getMobilePhone())) {
                FwUserEntity byMobilePhone = fwUserService.findByMobilePhon(fwUserEntity.getMobilePhone());
                if (!StringUtils.isEmpty(byMobilePhone)) {
                    return RestResponse.fail("手机号已存在");
                }
            }
            fwUserService.saveUser(fwUserEntity);
            response = RestResponse.succeed("注册成功!");
        } catch (Exception e) {
            String errorMessage = "注册失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 分页查询用户
     *
     * @return
     */
    @GetMapping("page")
    public RestResponse getPage(HttpServletRequest request, UserQueryVo userQueryVo) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            json = fwUserService.getPage(request, userQueryVo, curPage, pageSize);
            json.put("message", "查询成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /***
     * 查看个人信息
     * @param userId
     * @return
     */
    @GetMapping("{userId}")
    public RestResponse getUserInfo(@PathVariable("userId") String userId) {
        RestResponse response = null;
        try {
            FwUserEntity fwUserEntity = fwUserService.findByUserId(userId);
            response = RestResponse.succeed(fwUserEntity);
        } catch (Exception e) {
            String errorMessage = "查询信息失败";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }


    /**
     * 物理删除房屋用户(只删除fw_user表的用户)
     *
     * @param ids
     * @return
     */
    @PostMapping("deleteFwUser")
    public RestResponse deleteFwUser(@RequestBody String ids) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            List<String> idList= Arrays.asList(ids.split(","));
            fwUserService.deleteFwUser(idList);
            json.put("message", "删除用户成功");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errormessage = "删除用户失败";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * 批量逻辑删除用户（包含fw和sys的用户）
     *
     * @param ids
     * @return
     */
    @DeleteMapping("delete")
    public RestResponse deleteFwAndSysUser(@RequestParam List<String> ids) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            fwUserService.deletUser(ids);
            json.put("message", "删除用户成功");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errormessage = "删除用户失败";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /***
     * App端登录
     * @param userName
     * @param password
     * @return
     */
    @GetMapping("doLogin")
    public RestResponse doLogin(HttpServletRequest request, String userName, String password) {
        HttpSession session = request.getSession();
        Map<String, String> keyMap = LoginSecretPool.getKeys();
        session.setAttribute("PLATFORM_RSAMAP", keyMap);
        String privateKey = keyMap.get("privateKey");
        if (StringUtils.isEmpty(userName)) {
            return RestResponse.fail("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            return RestResponse.fail("密码不能空");
        }
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            PwdCheck pwdCheck = fwUserService.doLogin(userName, password, privateKey);
            if (pwdCheck.isSuccess()) {
                session.setAttribute("userId", pwdCheck.getUserId());
                session.setAttribute("token", pwdCheck.getToken());
                json.put("message", "登陆成功");
                response = RestResponse.succeed(json);
            } else {
                response = RestResponse.fail(pwdCheck.getErrorMessage());
            }
        } catch (Exception e) {
            String errormessage = "登录失败";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * 审核用户
     *
     * @param type
     * @param ids
     * @return
     */
    @PostMapping("{ids}/{type}")
    public RestResponse SHUser(@PathVariable("ids") String ids, @PathVariable("type") String type) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        try {
            fwUserService.updateType(type, list);
            json.put("message", "审核成功");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errormessage = "审核失败";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /***
     * 修改用户
     * @param userEntity
     * @return
     */
    @PutMapping
    public RestResponse update(@RequestBody UserEntity userEntity) {
        RestResponse restResponse = null;
        JSONObject object = new JSONObject();
        try {
            fwUserService.updateUser(userEntity);
            object.put("message", "修改用户成功");
            restResponse = RestResponse.succeed(object);
        } catch (Exception e) {
            String errormessage = "修改失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);

        }
        return restResponse;
    }

    /**
     * 获取用户所属省份
     *
     * @param request
     * @return
     */
    @GetMapping("/getAddre")
    public RestResponse getUserAddre(HttpServletRequest request) {
        String userId = PlatformSessionUtils.getUserId();
        DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
        String divisionId = mainDept.getDivisionId();
        if (StringUtils.isEmpty(divisionId)) {
            return RestResponse.succeed();
        } else {
            DivisionEntity division = divisionService.getDivision(divisionId);
            String divisionLevel = division.getDivisionLevel();
            String divisionName = null;
            if ("0".equals(divisionLevel) || "1".equals(divisionLevel)) {
                divisionName = division.getDivisionName();
            } else {
                String parentId = division.getParentId();
                DivisionEntity divisionEntity = divisionService.getDivision(parentId);
                String entityDivisionLevel = divisionEntity.getDivisionLevel();
                if ("0".equals(entityDivisionLevel) || "1".equals(entityDivisionLevel)) {
                    divisionName = divisionEntity.getDivisionName();
                } else {
                    String entityParentId = divisionEntity.getParentId();
                    DivisionEntity divisionServiceDivision = divisionService.getDivision(entityParentId);
                    String divisionDivisionLevel = divisionServiceDivision.getDivisionLevel();
                    if ("0".equals(divisionDivisionLevel) || "1".equals(divisionDivisionLevel)) {
                        divisionName = divisionServiceDivision.getDivisionName();
                    }
                }

            }
            return RestResponse.succeed(divisionName);
        }
    }
}
